<?php 
namespace app\admin\controller;

use think\Db;
use think\Session;

class Help extends Base {

	//模板展示页
	public function index() {
		$arr['name'] = input('name');
		$arr['dept'] = input('dept');
		$where = [];
		if(!empty($arr['name'])){
			$where['t.name'] = ['like','%' . $arr['name'] . '%'];
		}

		if(!empty($arr['dept'])){
			$where['d.id'] = $arr['dept'];
		}
		$data = Db::name('template')->alias('t')
				->join('dept d','t.create_dept_id = d.id','left')
				->where($where)
				->field('t.id,t.name,t.content,t.url,t.create_time,d.name as dept_name')
				->order('t.id desc')->paginate(config('paginate.list_rows'), false, ['query' => get_query()]);
		$page = $data->render();
		$dept = Db::name('dept')->where('isvalid',1)->column('id,name');
		//检测新增和删除的权限
		$uid = Session::get('userinfo.id');
        $auth = new Auth();
        $add = 0;
        $del = 0;

        if ($auth->check('admin/Help/add', $uid)) {
            $add = 1;
        }

        if ($auth->check('admin/Help/del', $uid)) {
            $del = 1;
        }
        $this->assign('add', $add);
        $this->assign('del', $del);
		$this->assign('data', $data);
		$this->assign('page', $page);
		$this->assign('dept',$dept);
		$this->assign('arr',$arr);
		return $this->fetch();
	}

	//新增模板页面
	public function add(){

		return $this->fetch();
	}

	//处理新增
	public function doAdd(){
		$data = input();
		$result = $this->validate($data, 'Template');

        if (true !== $result) {
            $this->error($result);
        }
    	$data['create_time'] = time();
    	$userinfo = Session::get('userinfo');
    	$data['create_uid'] = $userinfo['id'];
    	$data['create_dept_id'] = $userinfo['dept_id'];
		$info = Db::name('template')->insert($data);

    	if($info){
    		$this->success('添加成功', url('admin/Help/index'));
    	}else{
    		$this->success('添加失败');
    	}

	}

	//删除
	public function del(){
		$id = input('id');
		$info = Db::name('template')->where('id',$id)->delete();

		if($info){
			$this->success('删除成功!');
		}else{
			$this->error('删除失败!');
		}
	}
}
